<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="关联用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入关联用户ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="转账时的手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入转账时的手机号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="充值额度" prop="amount">
        <el-input
          v-model="queryParams.amount"
          placeholder="请输入充值额度"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" style="margin-top: 30px;">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['checksystem:record:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['checksystem:record:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['checksystem:record:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['checksystem:record:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div class="el-table-wrapper">
    <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户ID" align="center" prop="userId" />
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="充值金额" align="center" prop="amount" />
      <el-table-column label="充值套餐详情" align="center" prop="packageDetails" min-width="200">
        <template #default="scope">
          <span v-html="formatPackageDetails(scope.row.packageDetails)"></span>
        </template>
      </el-table-column>
      <el-table-column label="充值时间" align="center" prop="transferTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.transferTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="到期时间" align="center" prop="expirationTime" width="180">
        <template #default="scope">
          <span>{{ scope.row.expirationTime || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="删除标记" align="center" prop="isDeleted">
        <template #default="scope">
            <el-tag :type="scope.row.isDeleted === 1 ? 'danger' : 'success'">
              {{ scope.row.isDeleted === 1 ? '是' : '否' }}
            </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['checksystem:record:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['checksystem:record:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    </div>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
      class="pagination-container"
    />

    <!-- 添加或修改充值记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="recordRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="关联用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入关联用户ID" />
        </el-form-item>
        <el-form-item label="转账时的手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入转账时的手机号" />
        </el-form-item>
        <el-form-item label="充值额度" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入充值额度" />
        </el-form-item>
        <el-form-item label="充值套餐详情" prop="packageDetails">
          <div v-if="form.packageDetails" class="formatted-package-details" v-html="formatPackageDetails(form.packageDetails)"></div>
          <el-input v-model="form.packageDetails" type="textarea" placeholder="请输入JSON格式的套餐详情" />
        </el-form-item>
        <el-form-item label="到期时间" prop="updateTime">
          <el-date-picker clearable
            v-model="form.updateTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择到期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="转账时间" prop="transferTime">
          <el-date-picker clearable
            v-model="form.transferTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择转账时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否删除" prop="isDeleted">
          <el-checkbox-group v-model="form.isDeleted">
            <el-checkbox
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.value">
              {{dict.label}}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Record">
import { listRecord, getRecord, delRecord, addRecord, updateRecord } from "@/api/checksystem/record";
import { useDict } from '@/utils/dict';
import { parseTime } from '@/utils/ruoyi';
import { getUserLatestPackage } from "@/api/checksystem/package";

const { proxy } = getCurrentInstance();
const { sys_yes_no } = useDict("sys_yes_no");
const dict = reactive({
  sys_yes_no
});

const recordList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {
    id: null,
    userId: null,
    phone: null,
    amount: null,
    packageDetails: null,
    transferTime: null,
    createTime: null,
    updateTime: null,
    isDeleted: 0
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    phone: null,
    amount: null,
    packageDetails: null,
    transferTime: null,
    isDeleted: null
  },
  rules: {
    userId: [
      { required: true, message: "用户ID不能为空", trigger: "blur" }
    ],
    phone: [
      { required: true, message: "手机号不能为空", trigger: "blur" },
      { pattern: /^1[3-9]\d{9}$/, message: "手机号格式不正确", trigger: "blur" }
    ],
    amount: [
      { required: true, message: "充值点数不能为空", trigger: "blur" }
    ],
    transferTime: [
      { required: true, message: "转账时间不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

const columns = ref([
  { key: 0, label: `用户ID`, visible: true },
  { key: 1, label: `手机号`, visible: true },
  { key: 2, label: `金额`, visible: true },
  { key: 3, label: `充值套餐详情`, visible: true },
  { key: 4, label: `转账时间`, visible: true },
  { key: 5, label: `创建时间`, visible: true },
  { key: 6, label: `到期时间`, visible: true }
]);

/** 查询充值记录列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listRecord(queryParams.value);
    if (res.rows && res.rows.length > 0) {
      // 按照时间排序所有充值记录（最新的在前面）
      res.rows.sort((a, b) => {
        return new Date(b.transferTime) - new Date(a.transferTime);
      });
      
      // 用户ID到最新到期时间的映射
      const userEndTimeMap = new Map();
      
      // 处理每条记录
      res.rows.forEach(record => {
        // 确保packageDetails正确解析并保留单次充值积分
        if (typeof record.packageDetails === 'string') {
          try {
            // 先尝试从原始字符串中提取单次充值积分
            const pointsMatch = record.packageDetails.match(/"points"\s*:\s*(\d+)/);
            if (pointsMatch && pointsMatch[1]) {
              // 保存原始的单次充值积分值
              const originalPoints = parseInt(pointsMatch[1]);
              
              // 解析JSON
              const parsedPackageDetails = JSON.parse(record.packageDetails);
              
              // 为了确保显示单次充值积分，添加originalPoints属性
              if (originalPoints > 0) {
                parsedPackageDetails.originalPoints = originalPoints;
              }
              
              record.packageDetails = parsedPackageDetails;
            } else {
              // 如果无法从字符串提取，直接解析JSON
              record.packageDetails = JSON.parse(record.packageDetails);
            }
          } catch (error) {
            console.error('解析packageDetails失败:', error);
          }
        }
        
        // 正确的到期时间计算逻辑，基于充值记录而非当前套餐
        if (record.packageDetails && record.packageDetails.duration) {
          const duration = record.packageDetails.duration;
          const days = parseInt(duration.replace(/[^\d]/g, ''));
          
          if (!isNaN(days)) {
            const userId = record.userId;
            const transferDate = new Date(record.transferTime);
            
            // 获取此用户上一次的到期时间（如果有）
            let lastEndTime = userEndTimeMap.get(userId);
            
            // 计算新的到期时间
            let newEndTime;
            
            if (lastEndTime && lastEndTime > transferDate) {
              // 如果上一次的到期时间还未过期，则在其基础上叠加
              newEndTime = new Date(lastEndTime);
              newEndTime.setDate(newEndTime.getDate() + days);
            } else {
              // 如果没有上一次记录或已过期，则从转账时间开始计算
              newEndTime = new Date(transferDate);
              newEndTime.setDate(newEndTime.getDate() + days);
            }
            
            // 更新记录的到期时间
            record.expirationTime = parseTime(newEndTime);
            
            // 更新用户的最新到期时间
            userEndTimeMap.set(userId, newEndTime);
          }
        }
      });
    }
    recordList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('获取充值记录列表失败:', error);
  } finally {
    loading.value = false;
  }
};

/**
 * 格式化套餐详情为人类可读格式
 * @param {string} packageDetailsStr 套餐详情JSON字符串
 * @returns {string} 格式化后的套餐详情
 */
function formatPackageDetails(packageDetailsStr) {
  if (!packageDetailsStr) return "-";
  
  try {
    // 解析packageDetails
    let packageDetails;
    let inputPoints = 0; // 存储从原始字符串提取的积分值
    let displayPoints = 0; // 最终显示的积分值
    
    // 强制从原始字符串中提取points值，而非解析后的对象属性
    if (typeof packageDetailsStr === 'string') {
      // 使用正则表达式直接从字符串中提取 points 值
      const pointsMatch = packageDetailsStr.match(/"points"\s*:\s*(\d+)/);
      if (pointsMatch && pointsMatch[1]) {
        inputPoints = parseInt(pointsMatch[1]);
      }
      
      // 然后进行正常的JSON解析
      packageDetails = JSON.parse(packageDetailsStr);
      
      // 如果成功提取到积分值，使用它而不是packageDetails中的值
      displayPoints = inputPoints > 0 ? inputPoints : (packageDetails.points || 0);
    } else {
      packageDetails = packageDetailsStr;
      displayPoints = packageDetails.points || 0;
    }
    
    // 使用表格样式展示套餐详情
    return `<table class="record-package-table">
              <tr>
                <td class="record-pkg-label">价格</td>
                <td class="record-pkg-value">${packageDetails.price} 元</td>
              </tr>
              <tr>
                <td class="record-pkg-label">积分</td>
                <td class="record-pkg-value">${displayPoints} 点</td>
              </tr>
              <tr>
                <td class="record-pkg-label">有效期</td>
                <td class="record-pkg-value">${packageDetails.duration}</td>
              </tr>
            </table>`;
  } catch (error) {
    console.error("解析packageDetails失败:", error);
    return packageDetailsStr; // 解析失败时返回原字符串
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    phone: null,
    amount: null,
    packageDetails: null,
    transferTime: null,
    createTime: null,
    updateTime: null,
    isDeleted: 0
  };
  proxy.resetForm("recordRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加充值记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getRecord(_id).then(response => {
    form.value = response.data;
    form.value.isDeleted = response.data.isDeleted === 1 ? 1 : 0;
    open.value = true;
    title.value = "修改充值记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["recordRef"].validate(valid => {
    if (valid) {
      // 确保isDeleted是整数类型
      form.value.isDeleted = Number(form.value.isDeleted);
      
      if (form.value.id != null) {
        updateRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除充值记录编号为"' + _ids + '"的数据项？').then(function() {
    return delRecord(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('checksystem/record/export', {
    ...queryParams.value
  }, `record_${new Date().getTime()}.xlsx`)
}

getList();
</script>

<style>
.mb8 {
  margin-bottom: 8px;
}

.dialog-footer {
  text-align: center;
}

/* 表单样式 */
.el-form--inline {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 15px;
}

.el-form--inline .el-form-item {
  margin: 0;
  display: flex;
  align-items: center;
}

.el-form-item__label {
  white-space: nowrap;
  min-width: 120px;
  line-height: 32px;
}

.el-form-item__content {
  display: flex;
  align-items: center;
}

.el-input__wrapper,
.el-date-editor {
  width: 200px;
  height: 32px;
}

/* 分页样式 */
.pagination-container {
  position: fixed;
  bottom: 0;
  left: 200px;
  right: 0;
  background-color: #fff;
  padding: 15px 20px;
  box-shadow: 0 -2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1000;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  border-top: 1px solid #dcdfe6;
}

/* 表格容器样式 */
.el-table-wrapper {
  margin-bottom: 80px;
}

/* 套餐详情样式 */
.formatted-package-details {
  padding: 8px;
  margin-bottom: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #606266;
  font-size: 14px;
  line-height: 1.8;
  white-space: pre-line;
}

.package-details-cell {
  text-align: left;
  padding: 0 5px;
  line-height: 1.5;
}

/* 套餐详情表格样式 */
.record-package-table {
  width: 100%;
  border-collapse: collapse;
  border: none;
  background-color: #f8f9fa;
  font-size: 14px;
  color: #606266;
  border-radius: 4px;
  overflow: hidden;
}

.record-package-table tr {
  border-bottom: 1px solid #ebeef5;
}

.record-package-table tr:last-child {
  border-bottom: none;
}

.record-pkg-label {
  width: 80px;
  padding: 8px 15px;
  color: #909399;
  font-weight: normal;
  text-align: right;
  background-color: #f2f6fc;
}

.record-pkg-value {
  padding: 8px 15px;
  color: #303133;
  font-weight: 500;
}
</style>
